package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.WorkAssignedAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.AssignedBean;
import com.renwei.yunlong.bean.MuchAssignedBean;
import com.renwei.yunlong.bean.ReturnBean;
import com.renwei.yunlong.bean.WorkAssignedBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * 指派给 页面
 * <p>
 * Created by Administrator on 2017/10/10.
 */

public class WorkAssignedActivity extends BaseActivity implements HttpTaskListener, View.OnClickListener, BaseRecyclerViewAdapter.OnItemClickLitener {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.btn_confirm)
    Button btnConfirm;
    @Bind(R.id.recyclerView)
    XRecyclerView recyclerView;
    @Bind(R.id.ll_root)
    LinearLayout llRoot;
    private String requestId;
    private String outsourceFlag;
    private WorkAssignedAdapter adapter;
    private int mPosition;
    private int count = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assigned);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        requestId = getIntent().getStringExtra("requestId");
        outsourceFlag = getIntent().getStringExtra("outsourceFlag");
        initView();
        initData();
    }

    private void initView() {
        TextView titleView = simpleTileView.getTitleView();
        Drawable titleLeft =getResources().getDrawable(R.mipmap.icon_title_help);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        titleView.setCompoundDrawables(null, null, titleLeft, null);
        titleView.setCompoundDrawablePadding(10);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setPullRefreshEnabled(false);
        adapter = new WorkAssignedAdapter(this);
        adapter.setOnItemClickLitener(this);
        btnConfirm.setOnClickListener(this);
        titleView.setOnClickListener(this);
    }

    private void addFootView() {
        View footView = getLayoutInflater().inflate(R.layout.view_much_add, llRoot, false);
        footView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (count < 10) {
                    count++;
                    simpleTileView.setTitle("指派给(" + count + "/10)");
                    adapter.addLastData(new MuchAssignedBean());
                } else {
                    showCenterInfoMsg("最多指派10条工单");
                }
            }
        });
        recyclerView.setFootView(footView);
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        if ("1".equals(companyType)) {
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
        } else if ("2".equals(companyType)) {
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
        }
        ServiceRequestManager.getManager().getWorkAssigned(this, JsonMapUtil.mapToJson(map), this);
    }

    private void setAssignedData(WorkAssignedBean.RowsBean bean) {
        if ("1".equals(bean.getIsLeader())) { // 普通工单
            simpleTileView.setTitle("指派给");
            addFootView();
        } else if ("2".equals(bean.getIsLeader())) { //主工单
            if (bean.getWorkNum() != 0) {
                count = bean.getWorkNum();
            }
            simpleTileView.setTitle("指派给(" + count + "/10)");
            addFootView();
        } else if ("3".equals(bean.getIsLeader())) { //副工单
            simpleTileView.setTitle("指派给");
            recyclerView.setAdapter(adapter);
            adapter.setLeader(false);
        }
        MuchAssignedBean item = new MuchAssignedBean();
        item.setOutsourceFlag(bean.getOutsourceFlag());
        item.setResponseUserName(bean.getResponseUserName());
        item.setResponseUserId(bean.getResponseUserId());
        item.setRequestId(bean.getRequestId());
        item.setWorkOrder(bean.getWorkOrder());
        adapter.addLastData(item);
        // 添加 副处理人数据
        if ("2".equals(bean.getIsLeader()) && bean.getDesignList() != null && bean.getDesignList().size() != 0) { //主工单
            List<MuchAssignedBean> list = bean.getDesignList();
            for (MuchAssignedBean assignedBean : list) {
                assignedBean.setState(true);
            }
            adapter.addAll(list);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm:
                List<MuchAssignedBean> list = adapter.getData();
                HashMap<String, String> map = new HashMap<>();
                // 副处理人数据
                List<AssignedBean> designList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    MuchAssignedBean bean = list.get(i);
                    if (!bean.isState() && TextUtils.isEmpty(bean.getResponseUserName())) {
                        showCenterInfoMsg("请选择处理人");
                        return;
                    }
                    if (i > 0 && !bean.isState()) {
                        designList.add(new AssignedBean(bean.getResponseUserId(), bean.getResponseDes()));
                    }
                }
                map.put("designList", new Gson().toJson(designList));
                // 主处理人数据
                MuchAssignedBean leadBean = list.get(0);
                map.put("requestId", requestId);
                map.put("responseUserId", leadBean.getResponseUserId());
                map.put("responseDes", leadBean.getResponseDes());
                if ("1".equals(companyType)) {
                    map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                    map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                } else if ("2".equals(companyType)) {
                    map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                    map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                }
                ServiceRequestManager.getManager().setWorkAssigned(this, JsonMapUtil.mapToJson(map), this);
                break;
            case R.id.option_textview_title:
                GuideWebActivity.openActivity(this, Api.$().GUIDE_ASSIGN_WORK_URI);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = null;
            if (data != null) {
                bundle = data.getExtras();
            }
            if (requestCode == 222) {
                // 筛选重复
                String employeeId = bundle.getString("employeeId");
                String name = bundle.getString("name");

                for (int i = 0; i < adapter.getData().size(); i++) {
                    MuchAssignedBean bean = adapter.getData().get(i);
                    if (employeeId.equals(bean.getResponseUserId()) && i != mPosition) {
                        showCenterInfoMsg(name + "重复指派");
                        return;
                    }
                }

                adapter.getItem(mPosition).setResponseUserName(name);
                adapter.getItem(mPosition).setResponseUserId(employeeId);
//                adapter.notifyDataSetChanged();
                adapter.notifyMyItemChanged(mPosition + 1);
            }
        }
    }

    @Override
    public void onItemClick(View view, final int position) {
        switch (view.getId()) {
            case R.id.iv_delete:
                count--;
                simpleTileView.setTitle("指派给(" + count + "/10)");
                adapter.removeData(position);
                break;
            case R.id.rl_person:
                mPosition = position;
                PersonSelectActivity.OpenActivity(this, PersonSelectActivity.FROM_DEAL, 222);
                break;
            case R.id.tv_work:
                WorkInformationActivity.OpenActivity(this, adapter.getItem(position).getRequestId(),
                        adapter.getItem(position).getRequestId(), outsourceFlag);
                break;
        }
    }


    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                WorkAssignedBean workAssignedBean = new Gson().fromJson(result, WorkAssignedBean.class);
                if (workAssignedBean.getMessage().getCode() == 200) {
                    setAssignedData(workAssignedBean.getRows());
                } else {
                    showCenterInfoMsg(workAssignedBean.getMessage().getMessage());
                }
                break;
            case 2:
                EventBus.getDefault().post(new WorkPageRefreshEvent());
                ReturnBean bean = new Gson().fromJson(result, ReturnBean.class);
                if (bean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("指派成功!");
                    finish();
                } else if (bean.getMessage().getCode() == 1009) {
                    showCenterInfoMsg("此工单不允许指派!");
                } else if (bean.getMessage().getCode() == 1004) {
                    showCenterInfoMsg("工单不存在");
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, String requestId, String outsourceFlag) {
        Intent i = new Intent(context, WorkAssignedActivity.class);
        i.putExtra("requestId", requestId);
        i.putExtra("outsourceFlag", outsourceFlag);
        context.startActivity(i);
    }

}
